#include <stdio.h>
#include "main.h"

#define ERROR 1
#define OK 0

int _create_tree(BiTreeNode ** root_pp, char * pre_order_seq, int * current_index){
    int  status_sub_tree ;
    if(pre_order_seq[*current_index] == '\0'){
        (*root_pp) = NULL;
        return OK;
    }
    if(pre_order_seq[*current_index] == '#'){
        (*root_pp) = NULL;
        *current_index += 1;
        return OK;
    }

    (*root_pp) = (BiTreeNode*) malloc(sizeof (BiTreeNode));
    if(!(*root_pp)) {
        printf("failed to allocate memory, now exit()");
        return ERROR;
    }
    (*root_pp)->data = pre_order_seq[*current_index];
    *current_index +=1 ;

    status_sub_tree = _create_tree(&((*root_pp)->leftChild),pre_order_seq,current_index);
    if(status_sub_tree ==ERROR) {
        return status_sub_tree;
    }
    status_sub_tree = _create_tree(&((*root_pp)->rightChild),pre_order_seq,current_index);
    if(status_sub_tree ==ERROR) {
        return status_sub_tree;
    }
    return OK;
}

void create_tree(BiTreeNode ** root_pp, char * pre_order_seq, int num_elements) {
    int num_scanned_chars  = 0;
    _create_tree(root_pp,pre_order_seq,&num_scanned_chars);

}

//使用visit(item)函数前序遍历二叉树t
void pre_order_traverse(BiTreeNode *t, void visit(DataType item))
{
    if(t == NULL){
        return;
    }
        visit(t->data);
        pre_order_traverse(t->leftChild,visit);
        pre_order_traverse(t->rightChild,visit);

}

//使用visit(item)函数中序遍历二叉树t
void in_order_traverse(BiTreeNode *t, void visit(DataType item))
{
    if(t == NULL){
        return;
    }
    in_order_traverse(t->leftChild,visit);
    visit(t->data);
    in_order_traverse(t->rightChild,visit);

}

//使用void visit(DateType item)函数后序遍历二叉树t
void post_order_traverse(BiTreeNode *t, void visit(DataType item))
{
    if(t == NULL){
        return;
    }
    post_order_traverse(t->leftChild,visit);
    post_order_traverse(t->rightChild,visit);
    visit(t->data);
}

int main(){
    char * pre_seq ="ABC##DE#G##F###";

    BiTreeNode * root_p;

    create_tree(&root_p, pre_seq, 15);

    pre_order_traverse(root_p,visit);
    printf("\n");
    in_order_traverse(root_p,visit);
    printf("\n");
    post_order_traverse(root_p,visit);

}